import { useEffect, useRef, useState } from "react";
import lessModule from "./index.module.less"
import {  message, Table } from "antd";;
import {  $EventBus_off, $EventBus_on } from "../../../../common/utils";

// 主页-头部菜单组件-表格组件
interface homePageTableComponentInterface {
    name: string
    isHideBothEnds?: boolean
    columnList: Array<object>
    isRowSelection?: boolean
    tableReferenceHeight?: number
    isHidePagination?: boolean
    pageNo?: number
    pageSize?: number
    sourceData: object
    highlightList?: Array<string>
    smallPaddingList?: Array<string>
    smallFontList?: Array<string>
    borderLeftList?: Array<string>
    borderRightList?: Array<string>
    borderBottomList?: Array<string>
    alignCenterList?: Array<string>
    alignRightList?: Array<string>
    fixedList?: Array<string>
    change_pagination?: Function
    change_selectedRowList?: Function
}
const HomePage_TableComponent: React.FC<homePageTableComponentInterface> = (props) => {

    const [selectedRowKeyList, setSelectedRowKeyList] = useState<Array<React.Key>>([]);
    const sourceData = useRef<object>(props.sourceData)
    const selectedRowList = useRef<Array<number>>([]);
    const change_selectedRow = (selectedRowKeys: Array<React.Key>, selectedRows: Array<object>) => {
        selectedRowList.current = selectedRows.map((item:object)=>item["id"])
        setSelectedRowKeyList([...selectedRowKeys])
    }

    const init_scroll = () => {
        const antTableWrapperDom = document.querySelector('.ant-table-wrapper') as HTMLElement

        if (antTableWrapperDom) {
            antTableWrapperDom.style.width = `calc(100% - (${props.isHideBothEnds ? '0' : '40px'}))`
        }
    }

    const change_scrollHeight = (gap: number = 0) => {
        const tbodyDom = document.querySelector('.ant-table-tbody') as HTMLElement
        const bodyDom = document.querySelector('.ant-table-body') as HTMLElement
        const tableHeight = document.querySelector('.ant-table-wrapper')?.clientHeight ?? 0
        const theadHeight = document.querySelector('.ant-table-thead')?.clientHeight ?? 0
        const scrollHeight = tableHeight - theadHeight - gap - 46 - 200
        tbodyDom.style.height = `${sourceData.current["list"]?.length ? 0 : scrollHeight}px`
        bodyDom.style.height = `${scrollHeight}px`

    }

    const reset_selectedRow = () => {
        sourceData.current = props.sourceData
        selectedRowList.current = []
        setSelectedRowKeyList([])
    }
    // 广播函数数据
    const eventBusFuncData = {
        // 监听头部操作高度，更新表格虚拟滚动的高度
        headerOperationHeight: (data:object) => {
            // 通过两边有没有留白，判断是不是主要的数据表格
            !props.isHideBothEnds && change_scrollHeight(data["data"]["height"])
        },
        // 头部菜单导出
        headerOperationExport: (data:object) => {
            selectedRowList.current.length ? props.change_selectedRowList?.(selectedRowList.current) : message.warning("请选择！")
        }
    }
    useEffect(() => {
        change_scrollHeight()
    }, [props.tableReferenceHeight])

    useEffect(() => {
        reset_selectedRow()
        change_scrollHeight()
    }, [props.sourceData])

    useEffect(() => {
        $EventBus_on(eventBusFuncData)
        init_scroll()
        return () => {
            $EventBus_off(eventBusFuncData)
        }
    }, [])


    return (
        <div className={lessModule["homePageTableComponent"]}>

            {
                !props.isHideBothEnds && <div className={lessModule["homePageTableComponent-bothEnds"]} style={{ height: document.querySelector('.ant-table-thead')?.clientHeight }} />
            }
            <Table rowKey={(record,idx) => `${idx}${props.name}${record["id"]}`}
                tableLayout="auto"
                
                columns={props.columnList}
                dataSource={props.sourceData?.['list'] ?? []}
                rowHoverable={false}
                scroll={{ x: "max-content", y: "max-content" }}
                rowSelection={props.isRowSelection ? {
                    selectedRowKeys: selectedRowKeyList,
                    onChange: change_selectedRow,
                } : undefined}
                components={{
                    header: {
                        cell: (data: object) => {
                            return <th {...data} style={{
                                right: props.fixedList?.includes(data['children'][1]) ? 5 : 0,
                                backgroundColor: props.highlightList?.includes(data['children'][1]) ? 'rgba(24, 144, 255, 0.04)' : '',
                                padding: props.smallPaddingList?.includes(data['children'][1]) || typeof data['children'][1] === "object" ? "3px 14px 4px" : '12px 11px',
                                fontSize: props.smallFontList?.includes(data['children'][1]) || typeof data['children'][1] === "object" ? 12 : 14,
                                fontWeight: props.smallFontList?.includes(data['children'][1]) || typeof data['children'][1] === "object" ? 400 : 600,
                                borderLeft: props.borderLeftList?.includes(data['children'][1]) ? "1px solid #DCDCDC" : "none",
                                borderBottom: props.borderBottomList?.includes(data['children'][1]) ? "1px solid #DCDCDC" : "none",
                                borderRight: props.borderRightList?.includes(data['children'][1]) ? "1px solid #DCDCDC" : "none",
                                textAlign: props.alignRightList?.includes(data['children'][1]) || typeof data['children'][1] === "object" ? "right"
                                    : props.alignCenterList?.includes(data['children'][1]) ? "center" : undefined,
                            }} />
                        },
                    },
                }}
                pagination={!props.isHidePagination && {
                    current: props.pageNo,
                    pageSize: props.pageSize,
                    total: props.sourceData["total"],
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: (total) => `共${total}条`,
                    onChange: (no, size) => props.change_pagination?.(no, size)
                }}
            />
            {
                !props.isHideBothEnds && <div className={lessModule["homePageTableComponent-bothEnds"]} style={{ height: document.querySelector('.ant-table-thead')?.clientHeight }} />
            }
        </div>

    )
}

export default HomePage_TableComponent